package cc.vv.baselibrary.activity;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cc.vv.baselibrary.R;
import cc.vv.baselibrary.adapter.BCImageAdapter;
import cc.vv.baselibrary.util.BCObjectProcessingUtil;
import cc.vv.baselibrary.util.ImgDownload;
import cc.vv.baselibrary.util.LKLogUtil;
import cc.vv.baselibrary.util.LKToastUtil;
import cc.vv.baselibrary.view.imgselector.utils.LKPermissionUtil;
import cc.vv.baselibrary.view.photoView.BCPhotoViewPager;
import cc.vv.baselibrary.view.photoView.ImageInfoObj;
import cc.vv.lkbasecomponent.base.ui.LKBaseActivity;

/**
 * 公共图片浏览Activity界面
 * Created by sun.li on 2017/10/11.
 */
public class BCImageDisplayActivity extends UtimingBaseActivity {

    private Context mContext;

    /**
     * Dialog布局父容器
     */
    private RelativeLayout rl_bcidd_layout;

    /**
     * Dialog背景布局
     */
    private RelativeLayout rl_bcidd_background_layout;

    /**
     * 公共图片展示ViewPager
     */
    private BCPhotoViewPager bc_view_pager_photo;

    /**
     * 公共图片展示数量指示器
     */
    private TextView mTvImageCount;

    private TextView mTvSaveImage;

    /**
     * Dialog关闭过程中屏蔽事件专用控件
     */
    private Button btn_bcidd_cancel_blocking_events;

    /**
     * 当前展示的图片位置
     */
    private int currentPosition = 0;

    /**
     * 图片展示适配器对象
     */
    private BCImageAdapter adapter;

    public static final String UrlsLogo = "UrlsLogo";

    public static final String CurrentPositionLogo = "CurrentPositionLogo";

    /**
     * 是否默认显示保存按钮
     */
    public static final String ShowSaveBtn = "ShowSaveBtn";


    /**
     * 图片地址路径集合
     */
    private List<String> urls;

    /**
     * 待展示图片对象集合
     */
    private List<ImageInfoObj> imageInfoObjList;

    /**
     * 是否默认显示保存按钮
     */
    private boolean isShowSaveBtn;


    @Override
    protected void initView(Bundle bundle) {
        super.initView(bundle);
        setContentView(R.layout.activity_bc_photo_layout);
        mContext = this;
        try {
            if (Build.VERSION.SDK_INT >= 21) {
                View decorView = getWindow().getDecorView();
                //让应用主题内容占用系统状态栏的空间,注意:下面两个参数必须一起使用 stable 牢固的
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                //设置状态栏颜色为需要的颜色
                getWindow().setStatusBarColor(Color.parseColor("#333333"));
            }
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
        rl_bcidd_layout = (RelativeLayout) findViewById(R.id.rl_bcidd_layout);
        rl_bcidd_background_layout = (RelativeLayout) findViewById(R.id.rl_bcidd_background_layout);
        bc_view_pager_photo = (BCPhotoViewPager) findViewById(R.id.bc_view_pager_photo);
        mTvImageCount = (TextView) findViewById(R.id.bc_tv_image_count);
        mTvSaveImage = (TextView) findViewById(R.id.bc_tv_save_image_photo);
        btn_bcidd_cancel_blocking_events = (Button) findViewById(R.id.btn_bcidd_cancel_blocking_events);
    }


    @Override
    protected void initData(Bundle bundle) {
        try {
            urls = null;
            try {
                urls = BCObjectProcessingUtil.objMandatoryConversionClass(getIntent().getSerializableExtra(UrlsLogo)
                        , new ArrayList<String>());
            } catch (Exception e) {
                e.printStackTrace();
            }
            isShowSaveBtn = getIntent().getBooleanExtra(ShowSaveBtn, true);
            if (isShowSaveBtn) {
                mTvSaveImage.setVisibility(View.VISIBLE);
            } else {
                mTvSaveImage.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
        if (urls == null) {
            urls = new ArrayList<>();
        }

        try {
            currentPosition = getIntent().getExtras().getInt(CurrentPositionLogo);
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
            currentPosition = 0;
        }
    }

    @Override
    protected void initAction(Bundle bundle) {
        btn_bcidd_cancel_blocking_events.setVisibility(View.GONE);
        if (getUrls() == null || getUrls().size() <= 0) {
            hide();
        }
        initViewPager();

        setCurrentPosition(currentPosition);
    }

    /**
     * 获取图片地址路径集合
     */
    public List<String> getUrls() {
        return urls;
    }

    /**
     * 设置图片地址路径集合
     */
    public void setUrls(List<String> urls) {
        this.urls = urls;
    }

    public List<ImageInfoObj> getImageInfoObjList() {
        return imageInfoObjList;
    }

    public void setImageInfoObjList(List<ImageInfoObj> imageInfoObjList) {
        this.imageInfoObjList = imageInfoObjList;
    }

    @Override
    protected void onStart() {
        super.onStart();
        whetherFullScreenDisplayNoticeBoard(true);
    }

    @Override
    protected void onPause() {
        overridePendingTransition(0, 0);
        super.onPause();
    }

    public void hide() {
        finish();
//        mTvSaveImage.setVisibility(View.GONE);
//        mTvImageCount.setVisibility(View.GONE);
//        btn_bcidd_cancel_blocking_events.setVisibility(View.VISIBLE);
//        btn_bcidd_cancel_blocking_events.bringToFront();
//        btn_bcidd_cancel_blocking_events.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
//        whetherFullScreenDisplayNoticeBoard(false);
//
//        Animation animation = AnimationUtils.loadAnimation(this,
//                R.anim.anim_window_bottom_dialog_cancel_alpha);
//        animation.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                bc_view_pager_photo.setVisibility(View.GONE);
//                finish();
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });
//        bc_view_pager_photo.startAnimation(animation);
//        rl_bcidd_background_layout.startAnimation(AnimationUtils.loadAnimation(this, R.anim.anim_window_bottom_dialog_cancel_alpha));
    }

    private void initViewPager() {
        if (getUrls() != null && getUrls().size() > 0) {
            adapter = new BCImageAdapter(getUrls(), this);

            adapter.setItemOnClick(new BCImageAdapter.ItemOnClick() {
                @Override
                public void onViewClick() {
                    hide();
                }
            });

            mTvImageCount.setText(currentPosition + 1 + "/" + getUrls().size());
            mTvImageCount.bringToFront();

            bc_view_pager_photo.setAdapter(adapter);
            bc_view_pager_photo.setCurrentItem(currentPosition, false);
            bc_view_pager_photo.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
                    currentPosition = position;
                    mTvImageCount.setText(currentPosition + 1 + "/" + getUrls().size());
                }
            });

            mTvSaveImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //保存按钮点击
                    String img_uri = getUrls().get(currentPosition);
                    saveImage(img_uri);
                }
            });
        }
    }

    /**
     * 保存图片
     */
    private void saveImage(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        boolean sdPermission = LKPermissionUtil.getInstance().requestSD((Activity) mContext);
        if (sdPermission) {
            if (url.startsWith("http")) {
                ImgDownload.downloadImg(this, url);
            } else {
                Bitmap bitmap = BitmapFactory.decodeFile(url);
                try {
                    ImgDownload.saveFile(bitmap, "");
                } catch (IOException e) {
                    LKLogUtil.e(e.getMessage(), e);
                }
                LKToastUtil.showToastShort(getString(R.string.img_save_locally_prompt));
//            LKToastUtil.showToastShort("图片已保存到本地");
            }
        }
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            int state = bundle.getInt("state");
            LKLogUtil.e("===state===" + state);
            switch (state) {
                case -2:
//                    LKToastUtil.showToastShort("图片已保存至" + BCFileBasePath.PATH_DOWNLOADER + "文件夹");
                    LKToastUtil.showToastShort(getString(R.string.img_save_locally_prompt));
                    break;
                case -4:
                    LKToastUtil.showToastShort("图片下载失败");
                    break;
                default:
                    break;
            }
        }
    };


    public int getCurrentPosition() {
        return currentPosition;
    }

    /**
     * 设置初始化加载显示的页码，从0开始（0为第1页），设置页码需要在setUrls方法之后设置
     */
    public void setCurrentPosition(int currentPosition) {
        if (urls != null) {
            if (currentPosition >= urls.size()) {
                currentPosition = urls.size() - 1;
            } else if (currentPosition < 0) {
                currentPosition = 0;
            }
        } else {
            currentPosition = 0;
        }
        this.currentPosition = currentPosition;
    }

    /**
     * 是否全屏显示,true 全屏显示，不显示通知栏；false 不全屏显示，显示通知栏；
     */
    private void whetherFullScreenDisplayNoticeBoard(boolean enable) {
        try {
            if (enable) {
                //设置全屏
                this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            } else {
                //取消全屏
                this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                //得到当前界面的装饰视图
                if (Build.VERSION.SDK_INT >= 21) {
                    View decorView = getWindow().getDecorView();
                    //让应用主题内容占用系统状态栏的空间,注意:下面两个参数必须一起使用 stable 牢固的
                    int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                    decorView.setSystemUiVisibility(option);
                    //设置状态栏颜色为需要的颜色
                    getWindow().setStatusBarColor(Color.parseColor("#333333"));
                }
                ActionBar actionBar = getSupportActionBar();
                if (null != actionBar) {
                    actionBar.show();
                }
            }
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            hide();
        }
        return false;
    }

    @Override
    protected void onDestroy() {
//        TopPopTipDialogUtil.getInstance().setWhetherShowing(false);
        try {
            /*释放资源，避免OOM*/
            setContentView(R.layout.activity_jni_destruction_dedicated_null_layout);
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
        super.onDestroy();
    }
}
